# <template>
  <div class="work-records-view">
    <!-- 头部 -->
    <div class="view-header">
      <div class="header-left">
        <h3>工作记录</h3>
        <el-button link @click="$emit('close')">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      <div class="header-right">
        <span class="employee-name">{{ employee.username }}</span>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="dateShortcuts"
        @change="handleDateChange"
      />
      <el-button type="primary" @click="handleQuery">查询</el-button>
    </div>

    <!-- 统计区域 -->
    <div class="stats-section">
      <el-card>
        <div class="stats-grid">
          <div class="stat-item">
            <span class="label">总工资</span>
            <span class="value">¥{{ totalSalary }}</span>
          </div>
          <div class="stat-item">
            <span class="label">记录数</span>
            <span class="value">{{ totalRecords }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 记录列表 -->
    <div class="records-section">
      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedRecords.length">
        <el-alert
          :title="`已选择 ${selectedRecords.length} 条记录`"
          type="info"
          show-icon
        />
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
      </div>

      <!-- 记录列表 -->
      <el-table
        v-loading="loading"
        :data="sortedRecords"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-click="showRecordDetail"
        :row-style="{ cursor: 'pointer' }"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column 
          prop="createTime" 
          label="日期" 
          width="110"
          sortable
          :sort-orders="['ascending', 'descending']"
          @sort-change="handleSortChange"
        >
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="工作内容" min-width="150">
          <template #default="{ row }">
            <div class="record-content">
              <span class="record-type">{{ getRecordTypeText(row.type) }}</span>
              <span class="record-title">{{ getRecordTitle(row) }}</span>
              <el-tag 
                v-if="row.status === 0" 
                type="warning" 
                size="small"
              >待审核</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="60" align="right">
          <template #default="{ row }">
            {{ row.quantity || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="金额" width="60" align="right">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="60" fixed="right">
          <template #default="{ row }">
            <el-button link type="danger" @click.stop="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="记录详情"
      width="100%"
      destroy-on-close
    >
      <div class="detail-content" v-if="currentRecord">
        <div class="detail-item">
          <span class="label">日期：</span>
          <span class="value">{{ formatDate(currentRecord.createTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">类型：</span>
          <span class="value">{{ getRecordTypeText(currentRecord.type) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">工作内容：</span>
          <span class="value">{{ currentRecord.workItemName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">数量：</span>
          <span class="value">{{ currentRecord.quantity || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">金额：</span>
          <span class="value">¥{{ currentRecord.totalAmount }}</span>
        </div>
        <div class="detail-item">
          <span class="label">状态：</span>
          <span class="value">{{ currentRecord.status === 0 ? '待审核' : '已审核' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">备注：</span>
          <span class="value">{{ currentRecord.remark || '无' }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button type="danger" @click="handleDelete(currentRecord)">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Close, Delete } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { getSalaryStats, deleteType1Record, deleteType2Record, batchDeleteType1, batchDeleteType2 } from '@/api/salary'

// Props
const props = defineProps({
  employee: {
    type: Object,
    required: true
  }
})

// Emits
const emit = defineEmits(['close'])

// 状态
const loading = ref(false)
const dateRange = ref([])
const records = ref([])
const totalSalary = ref(0)
const totalRecords = ref(0)
const selectedRecords = ref([])
const showDetailDialog = ref(false)
const currentRecord = ref(null)

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 排序相关
const sortOrder = ref(null)

// 根据排序规则处理数据
const sortedRecords = computed(() => {
  if (!sortOrder.value) {
    return records.value
  }
  
  return [...records.value].sort((a, b) => {
    const timeA = new Date(a.createTime).getTime()
    const timeB = new Date(b.createTime).getTime()
    return sortOrder.value === 'ascending' ? timeA - timeB : timeB - timeA
  })
})

// 获取记录列表
const fetchRecords = async () => {
  loading.value = true
  try {
    const params = {
      uid: props.employee.id
    }
    
    if (dateRange.value?.length === 2) {
      params.startTime = dayjs(dateRange.value[0]).format('YYYY-MM-DD 00:00:00')
      params.endTime = dayjs(dateRange.value[1]).format('YYYY-MM-DD 23:59:59')
    }

    const res = await getSalaryStats(params)
    if (res.code === 200) {
      records.value = res.data.workRecords || []
      totalSalary.value = res.data.totalAmount || 0
      totalRecords.value = records.value.length
    } else {
      ElMessage.error(res.message || '获取记录失败')
    }
  } catch (error) {
    console.error('获取记录失败:', error)
    ElMessage.error('获取记录失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 获取记录类型文本
const getRecordTypeText = (type) => {
  return type === 1 ? '计件' : '手添'
}

// 获取记录标题
const getRecordTitle = (record) => {
  if (record.type === 1) {
    return `${record.workItemName} x ${record.quantity}`
  }
  return record.workItemName
}

// 处理日期变化
const handleDateChange = () => {
  selectedRecords.value = []
}

// 处理查询
const handleQuery = () => {
  if (dateRange.value?.length !== 2) {
    ElMessage.warning('请选择日期范围')
    return
  }
  fetchRecords()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRecords.value = selection
}

// 显示记录详情
const showRecordDetail = (record) => {
  currentRecord.value = record
  showDetailDialog.value = true
}

// 删除记录
const handleDelete = async (record) => {
  try {
    await ElMessageBox.confirm('确定要删除该记录吗？')
    const deleteFunc = record.type === 1 ? deleteType1Record : deleteType2Record
    const res = await deleteFunc(record.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      showDetailDialog.value = false
      fetchRecords()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除记录失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRecords.value.length) return

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRecords.value.length} 条记录吗？`)
    
    // 将选中的记录按类型分组
    const type1Records = []
    const type2Records = []
    
    selectedRecords.value.forEach(record => {
      if (record.type === 1) {
        type1Records.push(record.id)
      } else if (record.type === 2) {
        type2Records.push(record.id)
      }
    })

    // 分别删除不同类型的记录
    const deletePromises = []
    
    if (type1Records.length > 0) {
      deletePromises.push(batchDeleteType1(type1Records))
    }
    
    if (type2Records.length > 0) {
      deletePromises.push(batchDeleteType2(type2Records))
    }
    
    const results = await Promise.all(deletePromises)
    if (results.every(res => res.code === 200)) {
      ElMessage.success('删除成功')
      selectedRecords.value = []
      fetchRecords()
    } else {
      ElMessage.error('部分记录删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  if (prop === 'createTime') {
    sortOrder.value = order
  }
}

onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
.work-records-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.view-header {
  background-color: #fff;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left h3 {
  margin: 0;
}

.employee-name {
  font-size: 14px;
  color: #666;
}

.filter-section {
  background-color: #fff;
  padding: 16px;
  display: flex;
  gap: 16px;
  align-items: center;
  margin-bottom: 16px;
}

.stats-section {
  padding: 0 16px;
  margin-bottom: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
}

.stat-item .label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-item .value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.records-section {
  flex: 1;
  padding: 16px;
  background-color: #fff;
  margin: 0 16px 16px;
  border-radius: 4px;
  overflow: auto;
}

.batch-actions {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.record-type {
  color: #666;
}

.record-title {
  font-weight: bold;
}

.detail-content {
  padding: 20px 0;
}

.detail-item {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  color: #666;
  width: 80px;
  flex-shrink: 0;
}

.detail-item .value {
  flex: 1;
  font-weight: bold;
}

/* 添加排序图标样式 */
:deep(.el-table .sort-caret) {

}

:deep(.el-table .ascending .sort-caret.ascending) {
  border-bottom-color: var(--el-color-primary);
}

:deep(.el-table .descending .sort-caret.descending) {
  border-top-color: var(--el-color-primary);
}
</style> 